//
// Created by wxd on 2025/8/31.
//

#include "ShaderManager.h"

void ShaderManager::addShader(const std::string &materialId, Shader* shader) {
    if (!isLocked()) {
        std::lock_guard<std::mutex> lock(mLock);
    }
    if (mSingleShaderMap.find(materialId) == mSingleShaderMap.end()) {
        mSingleShaderMap[materialId] = shader;
    } else {
        if (mSingleShaderMap[materialId]->getTraceId() != shader->getTraceId()) {
            mSingleShaderMap[materialId] = shader;
        }
    }
}

bool ShaderManager::contains(const std::string &materialId) {
    if (!isLocked()) {
        std::lock_guard<std::mutex> lock(mLock);
    }
    return mSingleShaderMap.find(materialId) != mSingleShaderMap.end();
}

bool ShaderManager::removeShader(const std::string &materialId) {
    if (!isLocked()) {
        std::lock_guard<std::mutex> lock(mLock);
    }
    if (contains(materialId)) {
        mSingleShaderMap.erase(materialId);
        return true;
    }
    return false;
}

Shader *ShaderManager::getShader(const std::string &materialId) {
    if (!isLocked()) {
        std::lock_guard<std::mutex> lock(mLock);
    }
    if (contains(materialId)) {
        return mSingleShaderMap[materialId];
    }
    return nullptr;
}

void ShaderManager::clear() {
    if (!isLocked()) {
        std::lock_guard<std::mutex> lock(mLock);
    }
    mSingleShaderMap.clear();
}